<template>
  <div class="canvas-tool">
    <div class="left-handler" v-if="false">
      <Tooltip :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="撤销">
        <IconBack class="handler-item" :class="{ 'disable': !canUndo }" @click="undo()" />
      </Tooltip>
      <Tooltip :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="重做">
        <IconNext class="handler-item" :class="{ 'disable': !canRedo }" @click="redo()" />
      </Tooltip>
    </div>
    <Dropdown :trigger="['click']">
        <div class="menu-item">
          <p>
            <span>
              <IconAddOne />
            </span> 
            <span> 
               <i class="iconfont icon-sanjiaoxing_shang down-size"></i>
            </span>
          </p>
          <p class="add_label">
            <span class="text">插入</span>
          </p>
        </div>
        <template #overlay>
          <Menu>
            <MenuItem>
              <span :class="{ 'active': creatingElement?.type === 'text' }"  @click="drawText()">
                   <i class = "iconfont handler-item icon-wenbenkuang"></i> 
                  文本框
              </span>
            </MenuItem>
            <MenuItem>
              <Popover trigger="click" v-model:visible="shapePoolVisiblerow">
                <template #content>
                  <ShapePool @select="shape => drawShape(shape,'row')" />
                </template>
                <IconGraphicDesign class="handler-item" :class="{ 'active': creatingElement?.type === 'shape' }" />
                形状
              </Popover>
            </MenuItem>
            <MenuItem>
               <FileInput @change="files => insertImageElement(files)" :upType="imagefile">
                 <IconPicture class="handler-item" />  图片
              </FileInput>
            </MenuItem>
            <MenuItem>
              <SubMenu>
                 <Dropdown   placement="topRight">
                      <span>
                        <IconChartProportion class="handler-item" /> 图表
                      </span>
                      <template #overlay>
                          <Menu >
                              <MenuItem class="line-div" v-for="(chart, index) in chartList" :key="index" @click="charts => { createChartElement(chart); chartPoolVisible = false }">
                                    <IconChartHistogram size="16" v-if="chart=='bar'"/> <span v-if="chart=='bar'">柱状图</span>
                                    <IconChartLine size="16" v-else-if="chart=='line'"/> <span v-if="chart=='line'">折线图</span>
                                    <IconChartPie size="16" v-else-if="chart=='pie'"/> <span v-if="chart=='pie'">饼状图</span>
                                    <IconChartHistogramOne size="16" v-else-if="chart == 'horizontalBar'" /> <span v-if="chart == 'horizontalBar'">条形图</span>
                                    <IconChartLineArea size="16" v-else-if="chart == 'area'" /><span v-if="chart == 'area'">面积图</span>
                                    <IconChartRing size="16" v-else-if="chart == 'ring'" /><span v-if="chart == 'ring'">圆环图</span>
                                    <IconChartScatter size="16" v-else-if="chart == 'scatter'" /><span v-if="chart == 'scatter'">散点图</span>
                              </MenuItem>
                          </Menu>
                      </template>
                   </Dropdown>
               </SubMenu>
            </MenuItem>
            <MenuItem>
              <Popover trigger="click" v-model:visible="tableGeneratorVisible">
                <template #content>
                  <TableGenerator
                    @close="tableGeneratorVisible = false"
                    @insert="({ row, col }) => { createTableElement(row, col); tableGeneratorVisible = false }"
                  />
                </template>
                <span>
                  <IconInsertTable class="handler-item" /> 表格
                </span>
              </Popover>
            </MenuItem>
            <MenuItem @click="latexEditorVisible = true" >
              <IconFormula class="handler-item" /> 公式
            </MenuItem>
            <MenuItem>
               <Popover trigger="click" v-model:visible="mediaInputVisible">
                <template #content>
                  <MediaInput 
                    @close="mediaInputVisible = false"
                    @insertVideo="src => { createVideoElement(src); mediaInputVisible = false }"
                    @insertAudio="src => { createAudioElement(src); mediaInputVisible = false }"
                  />
                </template>
                <IconVideoTwo class="handler-item" /> 视频
              </Popover>
            </MenuItem>
          </Menu>
        </template>
    </Dropdown>
    <div class="add-element-handler">
      <Tooltip :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="插入文字" v-if="false">
        <IconFontSize class="handler-item" :class="{ 'active': creatingElement?.type === 'text' }" @click="drawText()" />
      </Tooltip>
      <div class="menu-item" @click="drawText()" :class="{ 'active': creatingElement?.type === 'text' }">
        <p>
           <i class="iconfont icon-wenbenkuang" ></i> 
           <i class="iconfont icon-sanjiaoxing_shang down-size"></i>
        </p>
        <p class="add_label"> 
          <span>文本框</span> 
        </p>
      </div>
      <FileInput @change="files => insertImageElement(files)" v-if="false">
        <Tooltip :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="插入图片">
          <IconPicture class="handler-item" />
        </Tooltip>
      </FileInput>
      <Popover trigger="click" v-model:visible="shapePoolVisible">
        <template #content>
          <ShapePool @select="shape => drawShape(shape,'clum')" />
        </template>
        <!-- <Tooltip :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="插入形状">
          <IconGraphicDesign class="handler-item" :class="{ 'active': creatingElement?.type === 'shape' }" />
        </Tooltip> -->
        <div class="menu-item" :class="{ 'active': creatingElement?.type === 'shape' }">
            <p >
              <IconGraphicDesign class="handler-item"  />
              <i class="iconfont icon-sanjiaoxing_shang down-size"></i>
            </p>
            <p class="add_label">形状</p>
        </div>
      </Popover>
      <Popover trigger="click" v-model:visible="linePoolVisible" v-if="false">
        <template #content>
          <LinePool @select="line => drawLine(line)" />
        </template>
        <Tooltip :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="插入线条">
          <IconConnection class="handler-item" :class="{ 'active': creatingElement?.type === 'line' }" />
        </Tooltip>
      </Popover>
      <Popover trigger="click" v-model:visible="chartPoolVisible" v-if="false">
        <template #content>
          <ChartPool @select="chart => { createChartElement(chart); chartPoolVisible = false }" />
        </template>
        <Tooltip :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="插入图表">
          <IconChartProportion class="handler-item" />
        </Tooltip>
      </Popover>
      <Popover trigger="click" v-model:visible="tableGeneratorVisible" v-if="false">
        <template #content>
          <TableGenerator
            @close="tableGeneratorVisible = false"
            @insert="({ row, col }) => { createTableElement(row, col); tableGeneratorVisible = false }"
          />
        </template>
        <Tooltip :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="插入表格">
          <IconInsertTable class="handler-item" />
        </Tooltip>
      </Popover>
      <Tooltip :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="插入公式" v-if="false">
        <IconFormula class="handler-item" @click="latexEditorVisible = true" />
      </Tooltip>
      <Popover trigger="click" v-model:visible="mediaInputVisible" v-if="false">
        <template #content>
          <MediaInput 
            @close="mediaInputVisible = false"
            @insertVideo="src => { createVideoElement(src); mediaInputVisible = false }"
            @insertAudio="src => { createAudioElement(src); mediaInputVisible = false }"
          />
        </template>
        <Tooltip :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="插入音视频">
          <IconVideoTwo class="handler-item" />
        </Tooltip>
      </Popover>
    </div>
    <world-panle/>
    <div class="right-handler" v-if="false">
      <IconMinus class="handler-item viewport-size" @click="scaleCanvas('-')" />
      <Popover trigger="click" v-model:visible="canvasScaleVisible">
        <template #content>
          <div class="viewport-size-preset">
            <div 
              class="preset-item" 
              v-for="item in canvasScalePresetList" 
              :key="item" 
              @click="applyCanvasPresetScale(item)"
            >{{item}}%</div>
          </div>
        </template>
        <span class="text">{{canvasScalePercentage}}</span>
      </Popover>
      <IconPlus class="handler-item viewport-size" @click="scaleCanvas('+')" />
      <Tooltip :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="适应屏幕">
        <IconFullScreen class="handler-item viewport-size-adaptation" @click="resetCanvas()" />
      </Tooltip>
    </div>

    <Modal
      v-model:visible="latexEditorVisible" 
      :footer="null" 
      centered
      :width="880"
      destroyOnClose
    >
      <LaTeXEditor 
        @close="latexEditorVisible = false"
        @update="data => { createLatexElement(data); latexEditorVisible = false }"
      />
    </Modal>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useMainStore, useSnapshotStore } from '@/store'
import { PresetChartType } from '@/types/slides'
import { getImageDataURL } from '@/utils/image'
import { ShapePoolItem } from '@/configs/shapes'
import { LinePoolItem } from '@/configs/lines'
import useScaleCanvas from '@/hooks/useScaleCanvas'
import useHistorySnapshot from '@/hooks/useHistorySnapshot'
import useCreateElement from '@/hooks/useCreateElement'
import ShapePool from './ShapePool.vue'
import LinePool from './LinePool.vue'
import ChartPool from './ChartPool.vue'
import TableGenerator from './TableGenerator.vue'
import MediaInput from './MediaInput.vue'
import LaTeXEditor from '@/components/LaTeXEditor/index.vue'
import WorldPanle from './world.vue'
const mainStore = useMainStore()
const { creatingElement } = storeToRefs(mainStore)
const { canUndo, canRedo } = storeToRefs(useSnapshotStore())
const { redo, undo } = useHistorySnapshot()

const {
  scaleCanvas,
  setCanvasScalePercentage,
  resetCanvas,
  canvasScalePercentage,
} = useScaleCanvas()
const chartList: PresetChartType[] = ['bar', 'horizontalBar', 'line', 'area', 'scatter', 'pie', 'ring']
const canvasScalePresetList = [200, 150, 100, 80, 50]
const canvasScaleVisible = ref(false)

const applyCanvasPresetScale = (value: number) => {
  setCanvasScalePercentage(value)
  canvasScaleVisible.value = false
}

const {
  createImageElement,
  createChartElement,
  createTableElement,
  createLatexElement,
  createVideoElement,
  createAudioElement,
} = useCreateElement()

const insertImageElement = (files: FileList) => {
  const imageFile = files[0]
  if (!imageFile) return
  getImageDataURL(imageFile).then(dataURL => createImageElement(dataURL))
}

const shapePoolVisible = ref(false)
const shapePoolVisiblerow = ref(false)
const linePoolVisible = ref(false)
const chartPoolVisible = ref(false)
const tableGeneratorVisible = ref(false)
const mediaInputVisible = ref(false)
const latexEditorVisible = ref(false)
const imagefile = 'image'
const videofile = 'video'
// 绘制文字范围
const drawText = () => {
  mainStore.setCreatingElement({
    type: 'text',
  })
  mainStore.setShadow(false)
}

// 绘制形状范围
const drawShape = (shape: ShapePoolItem, type: string) => {
  mainStore.setCreatingElement({
    type: 'shape',
    data: shape,
  })
  if (type === 'row') {
    shapePoolVisiblerow.value = false
  }
  else {
    shapePoolVisible.value = false
  }
}

// 绘制线条路径
const drawLine = (line: LinePoolItem) => {
  mainStore.setCreatingElement({
    type: 'line',
    data: line,
  })
  linePoolVisible.value = false
}
</script>

<style lang="scss" scoped>
.canvas-tool {
  position: relative;
  border-bottom: 1px solid $borderColor;
  background-color: #fff;
  display: flex;
  justify-content: flex-start;
  padding: 0 10px;
  font-size: 13px;
  user-select: none;
}
.left-handler {
  display: flex;
  align-items: center;
}
.menu-item {
  width: 60px;
  text-align: center;
  display: flex;
  cursor: pointer;
  justify-content: center;
  flex-direction: column;
  .add_label {
    margin-top: 3px;
    font-size: 10px;
  }
  .down-size {
    font-size: 10px;
    margin-left: 1px;
  }
}
.add-element-handler {
  // position: absolute;
  // top: 50%;
  // left: 50%;
  // transform: translate(-50%, -50%);
  display: flex;
}
.handler-item {
  margin: 0 10px;
  font-size: 14px;
  cursor: pointer;

  &.disable {
    opacity: .5;
  }
  &.active {
    color: $themeColor;
  }
}
.right-handler {
  display: flex;
  align-items: center;
  .text {
    width: 40px;
    text-align: center;
    cursor: pointer;
    margin-top: 2px;
  }
  .viewport-size {
    font-size: 13px;
  }
}
.preset-item {
  padding: 8px 20px;
  text-align: center;
  cursor: pointer;

  &:hover {
    color: $themeColor;
  }
}
</style>